#include<string.h>

#include "UI.h"


inline struct RGB* get_i_j_rgb(struct rgb_info *rgb_obj, int row_num, int col_num);
inline struct RGBA* get_i_j_rgba(struct rgba_info *rgba_obj, int row_num, int col_num);

void inputRGBA2RGB(struct rgba_drawing_info *rgba_draw_obj, struct rgb_info *tar_obj)
{
    int i, j;
    int _tarHeight, _tarWidth;
    int _srcHeight, _srcWidth;
    int top, left;

    _tarHeight = rgba_draw_obj->dest_pos.height;
    _tarWidth  = rgba_draw_obj->dest_pos.width;
    _srcHeight = rgba_draw_obj->rgba_obj.height;
    _srcWidth  = rgba_draw_obj->rgba_obj.width;
    top       = rgba_draw_obj->dest_pos.top;
    left      = rgba_draw_obj->dest_pos.left;

    // 融合图像
    if(top + _tarHeight > tar_obj->height || left + _tarWidth > tar_obj->width)
    {
        printf("Error!The picture is over the layer\n");
        return;
    }
    for(i=0;i<_tarHeight;i++)
    {
        for(j=0;j<_tarWidth;j++)
        {
            unsigned char _alpha = get_i_j_rgba(&(rgba_draw_obj->rgba_obj), i*_srcHeight/_tarHeight, j*_srcWidth/_tarWidth)->Alpha;
            get_i_j_rgb(tar_obj, i+top, j+left)->Red   = (get_i_j_rgba(&(rgba_draw_obj->rgba_obj), i*_srcHeight/_tarHeight,j*_srcWidth/_tarWidth)->Red*_alpha   + get_i_j_rgb(tar_obj, i+top, j+left)->Red  *(255-_alpha))/255;
            get_i_j_rgb(tar_obj, i+top, j+left)->Green = (get_i_j_rgba(&(rgba_draw_obj->rgba_obj), i*_srcHeight/_tarHeight,j*_srcWidth/_tarWidth)->Green*_alpha + get_i_j_rgb(tar_obj, i+top, j+left)->Green*(255-_alpha))/255;
            get_i_j_rgb(tar_obj, i+top, j+left)->Blue  = (get_i_j_rgba(&(rgba_draw_obj->rgba_obj), i*_srcHeight/_tarHeight,j*_srcWidth/_tarWidth)->Blue*_alpha  + get_i_j_rgb(tar_obj, i+top, j+left)->Blue *(255-_alpha))/255;
        }
    }
    free_rgba_mem(&(rgba_draw_obj->rgba_obj));
    
}

inline struct RGB *get_i_j_rgb(struct rgb_info *rgb_obj, int row_num, int col_num)
{
    struct RGB *src_rgb_ptr  = rgb_obj->rgb_buffer;
    return &(src_rgb_ptr[row_num*rgb_obj->width + col_num]);
}

inline struct RGBA *get_i_j_rgba(struct rgba_info *rgba_obj, int row_num, int col_num)
{
    struct RGBA *src_rgba_ptr  = rgba_obj->rgba_buffer;
    return &(src_rgba_ptr[row_num*rgba_obj->width + col_num]);
}

void inputStringObj(StringOBJ *_str_obj, struct rgb_info *tar_obj)
{
    int i, j;
    switchString2Mat(_str_obj);
    for(i=0;i<_str_obj->width;i++)
    {
        for(j=0;j<_str_obj->height;j++)
        {
            if(_str_obj->matBuff[i][j] != 0)
            {
                get_i_j_rgb(tar_obj, j+_str_obj->stringPos.top, i+_str_obj->stringPos.left)->Blue = _str_obj->fontRGB.Blue;
                get_i_j_rgb(tar_obj, j+_str_obj->stringPos.top, i+_str_obj->stringPos.left)->Red = _str_obj->fontRGB.Red;
                get_i_j_rgb(tar_obj, j+_str_obj->stringPos.top, i+_str_obj->stringPos.left)->Green = _str_obj->fontRGB.Green;
            }
        }
    }
    freeStringMem(_str_obj);
}